package com.wl156.activities;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.wl156.MyApp;
import com.wl156.lite.R;
import com.wl156.model.Certificate;
import com.wl156.model.User;
import com.wl156.model.WebServiceClient;
import com.wl156.utils.Utils;

public class MainTab extends TabActivity {

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;
	public static TabHost tabHost;

	private String mUserType;

	private AlertDialog mAlert;

	private TextView mUserPhone;
	private TextView mUserName;

	private TextView mTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.tab_main);

		mUserPhone = (TextView) findViewById(R.id.phone);
		mUserName = (TextView) findViewById(R.id.name);

		mTitle = (TextView) findViewById(R.id.title);

		final AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("还没登录，请先登录");
		builder.setPositiveButton("登录", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent i = new Intent(MainTab.this, Login.class);
				startActivity(i);
			}
		});
		builder.setNegativeButton("取消", null);
		mAlert = builder.create();

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		tabHost = getTabHost();
		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				if (tabId.equals("home")) {
					mTitle.setText("156物流网");
				} else if (tabId.equals("my156")) {
					mTitle.setText("我的156");
				} else if (tabId.equals("MessageCenter")) {
					mTitle.setText("信息中心");
				} else if (tabId.equals("Manual")) {
					mTitle.setText("使用指南");
				} else if (tabId.equals("quit")) {
					mTitle.setText("退出");
				}
				
				if (!((MyApp) getApplication()).isLogined()
						&& !tabId.equals("quit")) {
					if (!mAlert.isShowing()) {
						mAlert.show();
					}
					tabHost.setCurrentTabByTag("home");
				}
			}
		});

		TabSpec tab1 = tabHost.newTabSpec("my156");
		tab1.setIndicator(createTabView("我的156"));
		tab1.setContent(new Intent(this, My156.class));
		tabHost.addTab(tab1);

		TabSpec tab2 = tabHost.newTabSpec("MessageCenter");
		tab2.setIndicator(createTabView("信息中心"));
		tab2.setContent(new Intent(this, MessageListCenter.class));
		tabHost.addTab(tab2);

		TabSpec tab3 = tabHost.newTabSpec("Manual");
		tab3.setIndicator(createTabView("使用指南"));
		tab3.setContent(new Intent(this, SystemIntro.class));
		tabHost.addTab(tab3);

		TabSpec tab4 = tabHost.newTabSpec("home");
		tab4.setIndicator(createTabView("回主页面"));
		tab4.setContent(new Intent(this, HomeActivity.class));
		tabHost.addTab(tab4);

		TabSpec tab5 = tabHost.newTabSpec("quit");
		tab5.setIndicator(createTabView("退出"));
		tab5.setContent(new Intent(this, Quit.class));
		tabHost.addTab(tab5);

		tabHost.setCurrentTabByTag("home");

		new getUserInfoTask().execute();
	}

	private View createTabView(String title) {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.tab_widget_main, null);
		TextView tv = (TextView) view.findViewById(R.id.title);
		tv.setText(title);
		return view;
	}

	class getUserInfoTask extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;

		protected void onPreExecute() {
			mDialog = ProgressDialog.show(MainTab.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			mDialog.dismiss();

			if (result == null) {
				mAlert.show();
				return;
			}

			if (result instanceof SoapObject) {
				SoapObject so = (SoapObject) result;
				String name = so.getProperty(0).toString();
				if (name.equals("用户验证失败")) {
					Context mContext = MainTab.this;
					((MyApp) mContext.getApplicationContext()).logout();
					mContext.startActivity(new Intent(mContext, Login.class));
					((Activity) mContext).finish();
					return;
				}
				// 06-12 22:17:52.703: D/(7968): result: anyType{string=张利平;
				// string=0; string=0; string=0; string=广东珠海; string=0;
				// string=0; string=null; string=0; string=C; }, type:
				// SoapObject

				String creditScroe = Utils.propertyToShow(so.getProperty(1));
				String finishedOrderCount = Utils.propertyToShow(so
						.getProperty(2));
				String goingOrderCount = Utils
						.propertyToShow(so.getProperty(3));
				String curentPlace = Utils.propertyToShow(so.getProperty(4));
				String collectedTrunkCount = Utils.propertyToShow(so
						.getProperty(5));
				String collectedLineCount = Utils.propertyToShow(so
						.getProperty(6));
				String isInternalUser = Utils.propertyToShow(so.getProperty(7));
				String isSupportLogisticsCard = Utils.propertyToShow(so
						.getProperty(8));
				String type = Utils.propertyToShow(so.getProperty(9));
				mUserType = type;

				User user = new User();
				user.name = name;
				user.type = mUserType;
				user.phone = mCertificate.userLoginId;

				mUserPhone.setText(user.phone);
				mUserName.setText(user.name);

				((MyApp) getApplication()).setCurrentUser(user);

				if (mUserType.equals("C")) {
					// 公司
				} else {
					// 司机
				}
			} else {
				AlertDialog.Builder builder = new Builder(MainTab.this);
				builder.setMessage("网络请求超时！");
				builder.setPositiveButton("重试",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								new getUserInfoTask().execute();
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						});
				builder.show();
			}
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				return mWebServiceClient.commonGetPersonalInfo(mCertificate);
			} catch (IOException e) {
				e.printStackTrace();
				return e;
			} catch (XmlPullParserException e) {
				e.printStackTrace();
				return e;
			}
		}
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new Builder(MainTab.this);
		builder.setMessage("确定退出吗？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				MainTab.super.onBackPressed();
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}
}
